package jtalk.model;

import jtalk.controller.Properties;
import jtalk.logging.Logger;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;

public class ChatEventListener implements ChatManagerListener {

	private XMPPManager xmppManager;	

	protected ChatEventListener(XMPPManager xmppManager) {
		this.xmppManager = xmppManager;
	}
	
	
	public void chatCreated(Chat chat, boolean createdLocally) {
												
		chat.addMessageListener(new MessageListener() {

			public void processMessage(Chat chat, Message message) {
				
				if(message.getBody() != null && !message.getBody().equals("")) {
					
					Contact from = new Contact(message.getFrom());
					Contact to = new Contact(message.getTo());
					
					jtalk.model.Message msg = new jtalk.model.Message();
					msg.setFrom(from);
					msg.setTo(to);
					msg.setMessage(message.getBody());
					
					xmppManager.firePropertyChange(Properties.MESSAGE_IN.toString(), null, msg);
					
					Logger.getLogger(this).debug(msg + " body : " + msg.getMessage());
					
				}
																
			}			
		});		
	}

}
